#ifndef DATABASE_H
#define DATABASE_H

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

static bool createConnection(QString path)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(path);

    if (!db.open()) {
        QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
                QObject::tr("Unable to establish a database connection.\n"
                            "This example needs SQLite support. Please read "
                            "the Qt SQL driver documentation for information how "
                            "to build it.\n\n"
                            "Click Cancel to exit."), QMessageBox::Cancel);
        return false;
    }

    QStringList tables = db.tables();
    QSqlQuery query;

    //table of SWM_Task
    if(!tables.contains("SWM_Task",Qt::CaseInsensitive)) {
        if(!query.exec("create table SWM_Task(\
                ID INTEGER PRIMARY KEY AUTOINCREMENT,\
                TaskID INT,\
                Sequence INT,\
                Status varchar(20),\
                Model INT,\
                Time INT,\
                StartTime DATETIME,\
                EndTime DATETIME,\
                DetergentType varchar(20),\
                DetergentDose varchar(20),\
                Temperature Int)")) {
            return false;
        }
    }

    //table of SWM_TaskStatus
    if(!tables.contains("SWM_TaskStatus",Qt::CaseInsensitive)) {
        if(!query.exec("create table SWM_TaskStatus(\
                TaskID INTEGER PRIMARY KEY AUTOINCREMENT,\
                TaskStatus varchar(20),\
                StartTime DATETIME,\
                EndTime DATETIME)")) {
            return false;
        }
    }

    //table of SWM_TaskModel
    if(!tables.contains("SWM_TaskModel",Qt::CaseInsensitive)) {
       if(!query.exec("create table SWM_TaskModel(\
               ModelID INT primary key,\
               ModelName varchar(20))")) {
           return false;
       }
    }

    //table of SWM_Model
    if(!tables.contains("SWM_Model",Qt::CaseInsensitive)) {
      if(!query.exec("create table SWM_Model(\
              ID INTEGER PRIMARY KEY AUTOINCREMENT,\
              ModelID INT,\
              Sequence INT,\
              Model INT,\
              Time INT,\
              DetergentType varchar(20),\
              DetergentDose varchar(20),\
              Temperature Int)")) {
          return false;
      }
    }

     //table of SWM_ModelName
     if(!tables.contains("SWM_ModelName",Qt::CaseInsensitive)) {
       if(!query.exec("create table SWM_ModelName(\
               ModelID INTEGER PRIMARY KEY AUTOINCREMENT,\
               ModelName varchar(20))")) {
           return false;
       }
     }

    return true;
}

#endif // DATABASE_H
